package com.zhongxi.guoyuan.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhongxi.guoyuan.OffLineShop.UI.OffLineCateActivity;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.CategoryAdapter;
import com.zhongxi.guoyuan.adapter.ImageBannerAdapter;
import com.zhongxi.guoyuan.adapter.ad.JDViewAdapter;
import com.zhongxi.guoyuan.adapter.rewardCoin.RewardCoinAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseFragment;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.EventBusMessage;
import com.zhongxi.guoyuan.entity.ad.AdData;
import com.zhongxi.guoyuan.entity.ad.AdResult;
import com.zhongxi.guoyuan.entity.coinStore.HotGoodsData;
import com.zhongxi.guoyuan.entity.coinStore.HotGoodsResult;
import com.zhongxi.guoyuan.entity.projectItem.ProjectItemData;
import com.zhongxi.guoyuan.entity.projectItem.ProjectItemResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.ImageUtils;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.HtmlActivity;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.view.rewardCoin.HMActivity;
import com.zhongxi.guoyuan.view.rewardCoin.HotRewardCoinActivity;
import com.zhongxi.guoyuan.view.rewardCoin.RewardCateActivity;
import com.zhongxi.guoyuan.view.rewardCoin.RewardCoinDetailActivity;
import com.zhongxi.guoyuan.view.rewardCoin.SearchActivity;
import com.zhongxi.guoyuan.view.shopCart.ShoppingCartActivity;
import com.zhongxi.guoyuan.view.user.LoginActivity;
import com.zhongxi.guoyuan.widget.ViewFlow;
import com.zhongxi.guoyuan.widget.ViewFlowIndicator;
import com.zhongxi.guoyuan.widget.ad.JDAdverView;
import com.zhongxi.guoyuan.widget.goldshop.NoScrollGridView;
import com.zhongxi.guoyuan.widget.screenadaptaion.CustomRelativelayout;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class MainRewardCoinFragment extends BaseFragment implements View.OnClickListener, MyScrollView.OnScrollListener {

    private ViewFlow viewflow;
    private List<AdData> adData = new ArrayList<AdData>();
    private ImageBannerAdapter mBannerAdapter;
    private ArrayList<HotGoodsData> datas = new ArrayList<HotGoodsData>();
    private String type;
    private LinearLayout search_offline;
    private NoScrollGridView gvList;

    private ArrayList<ProjectItemData> projectItemDatas;
    private ImageView iv_shopCar;

    private PopupWindow popupWindow;
    private RelativeLayout rl_search;
    private boolean isMeasure;
    private int mMeasuredHeight;
    private MyScrollView mMyScrollView;
    private LinearLayout mLinearLayout;
    private LinearLayout mLinearBegin;
    private LinearLayout mScrollBody;
    private LinearLayout mLinearStop;
    private TextView mTv_new;
    private TextView mTv_hot;
    private TextView mTv_privilege;
    private int orderBy = 1;
    private RewardCoinAdapter mAdapter;
    private boolean isMore;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mView = inflater.inflate(R.layout.fragment_main_coin, container, false);
        return mView;
    }

    @Override
    protected void initView() {
        super.initView();
        initTitle();
        tvTitle.setText("线上赚豆超市");
        if (projectItemDatas == null) {
            projectItemDatas = new ArrayList<>();
        }
        ProjectItemData projectItemData = new ProjectItemData("0", "全部", "", true);
        projectItemDatas.add(projectItemData);
        //实现上拉布局悬停
        iv_shopCar = (ImageView) getView().findViewById(R.id.iv_shopCar);
        gvList = (NoScrollGridView) getView().findViewById(R.id.gvList);
        rl_search = (RelativeLayout) getView().findViewById(R.id.rl_search);
        search_offline = (LinearLayout) getView().findViewById(R.id.search_offline);
        mTv_new = (TextView) getView().findViewById(R.id.tv_new);
        mTv_hot = (TextView) getView().findViewById(R.id.tv_hot);
        mTv_privilege = (TextView) getView().findViewById(R.id.tv_privilege);

        //设置高度
        FrameLayout flow = (FrameLayout) getView().findViewById(R.id.flow);
        ImageUtils.setHeight(getActivity(), Constants.flowRate, flow);
        initSuspend();
    }

    private void initSuspend() {
        mMyScrollView = (MyScrollView) getView().findViewById(R.id.myScrollView);
        mLinearLayout = (LinearLayout) getView().findViewById(R.id.linearLayout);
        mLinearBegin = (LinearLayout) getView().findViewById(R.id.linearBegin);
        mScrollBody = (LinearLayout) getView().findViewById(R.id.scrollBody);
        mLinearStop = (LinearLayout) getView().findViewById(R.id.linearStop);
        mLinearLayout.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (!isMeasure) {
                    mMeasuredHeight = mLinearLayout.getMeasuredHeight();
                    isMeasure = true;
                }
                return true;
            }
        });
    }

    /**
     * 上下轮播
     *
     * @param data
     */
    private void initJDScroll(List<HotGoodsData> data) {
        datas.clear();
        datas.addAll(data);
        final JDViewAdapter jddapter = new JDViewAdapter(context, datas, 1);
        jddapter.setTitleData(projectItemDatas);
        final JDAdverView tbView = (JDAdverView) getView().findViewById(R.id.jdadver);
        tbView.setAdapter(jddapter);
        //开启线程滚动
        tbView.start();
    }

    /**
     * 左右轮播
     */
    private void initViewFlow() {
        /**
         * 轮播
         */
        viewflow = (ViewFlow) getView().findViewById(R.id.viewflow);
        ViewFlowIndicator viewflowdic = (ViewFlowIndicator) getView().findViewById(R.id.viewflowdic);
        viewflow.setFlowIndicator(viewflowdic);
        if (adData.size() > 0) {
            viewflow.setSideBuffer(adData.size()); // 实际图片数量
        } else {
            viewflow.setSideBuffer(1);
        }
        if (mBannerAdapter == null) {
            mBannerAdapter = new ImageBannerAdapter(getActivity(), adData, 3);
        } else {
            mBannerAdapter.replaceAll(adData);
        }
        viewflow.setAdapter(mBannerAdapter);
        viewflow.startAutoFlowTimer();
    }

    @Override
    protected void initData() {
        super.initData();
        mAdapter = new RewardCoinAdapter(context, datas);
        gvList.setAdapter(mAdapter);
        //获取广告
        showAds();
    }

    /**
     * 获取广告展示
     */
    private void showAds() {
        type = "showads";
        String getStr = "&type=3";
        getServer(Url.SHOW_ADS, null, getStr, false, null, "get");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("showads".equals(type)) {
                AdResult adResult = gson.fromJson(response, AdResult.class);
                if (adResult.getSafeobj() != null && !"".equals(adResult.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(adResult.getSafeobj());
                }
                adData.clear();
                adData.addAll(adResult.getData());
                initViewFlow();
                //获取商品分类列表
                getCategory();
            } else if ("category".equals(type)) {
                ProjectItemResult itemResult = gson.fromJson(response, ProjectItemResult.class);
                MyApplication.getInstance().setSpValue(itemResult.getSafeobj());
                if (itemResult.getData() != null && itemResult.getData().size() > 0) {
                    projectItemDatas.addAll(itemResult.getData());
                }
                //获取商品列表
                getGoodsList();
            } else if ("goodslist".equals(type)) {
                HotGoodsResult shopGoodsList = gson.fromJson(response, HotGoodsResult.class);
                MyApplication.getInstance().setSpValue(shopGoodsList.getSafeobj());
                if (pageNum == 1) {
                    datas.clear();
                }
                if (null != shopGoodsList.getData() && shopGoodsList.getData().size() > 0) {
                    datas.addAll(shopGoodsList.getData());
                    isMore = true;
                } else {
                    if (pageNum > 1) {
                        pageNum--;
                    }
                    isMore = false;
                }
                mAdapter.notifyDataSetChanged();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getCategory() {
        type = "category";
        getServer(Url.MALL_CATEGORY_LIST, null, "", false, null, "get");
    }

    /**
     * 获取商品列表  红豆
     */
    private void getGoodsList() {
        type = "goodslist";
        String str = "&cateid=0&goodstype=3&orderBy=" + orderBy + "&page=" + pageNum;
        getServer(Url.MALL_GOODS_LIST, null, str, false, null, "get");
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse result = gson.fromJson(response, BaseResponse.class);
        if (null != result.getSafeobj() && !"".equals(result.getSafeobj()))
            MyApplication.getInstance().setSpValue(result.getSafeobj());
        if (result.getCode() == 2101) {
            showShortToast("数据完善中，敬请期待");
        } else if (result.getCode() == 5000) {
            showShortToast("商品信息不完善");
        }
    }


    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        iv_shopCar.setOnClickListener(this);
        rl_search.setOnClickListener(this);
        search_offline.setOnClickListener(this);
        mMyScrollView.setOnScrollListener(this);
        mTv_new.setOnClickListener(this);
        mTv_hot.setOnClickListener(this);
        mTv_privilege.setOnClickListener(this);
        gvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(context, RewardCoinDetailActivity.class);
                intent.putExtra("gid", datas.get(i).getId());
                context.startActivity(intent);
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                getActivity().finish();
                break;
            case R.id.search_offline:
//                getPopupwindow(v);
                Intent mIntent = new Intent(UiUtils.getContext(), RewardCateActivity.class);
                mIntent.putExtra("catelist", projectItemDatas);
                startActivity(mIntent);
                break;
            case R.id.iv_shopCar:
                if (!TextUtils.isEmpty(MyApplication.getInstance().getUserId())) {
                    Intent intent = new Intent(context, ShoppingCartActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.putExtra("position", 1);
                    startActivity(intent);
                }
                break;
            case R.id.rl_search:
                startAct(SearchActivity.class);
                break;
            case R.id.tv_new:
                if (mScrollBody.getParent() != mLinearBegin) {
                    mMyScrollView.fullScroll(MyScrollView.FOCUS_UP);
                    mLinearStop.removeView(mScrollBody);
                    mLinearBegin.addView(mScrollBody);
                }
                mTv_new.setTextColor(getResources().getColor(R.color.title_red));
                mTv_hot.setTextColor(getResources().getColor(R.color.gohere));
                mTv_privilege.setTextColor(getResources().getColor(R.color.gohere));
                pageNum = 1;
                orderBy = 1;
                getGoodsList();
                break;
            case R.id.tv_hot:
                if (mScrollBody.getParent() != mLinearBegin) {
                    mMyScrollView.fullScroll(MyScrollView.FOCUS_UP);
                    mLinearStop.removeView(mScrollBody);
                    mLinearBegin.addView(mScrollBody);
                }
                mTv_new.setTextColor(getResources().getColor(R.color.gohere));
                mTv_hot.setTextColor(getResources().getColor(R.color.title_red));
                mTv_privilege.setTextColor(getResources().getColor(R.color.gohere));
                pageNum = 1;
                orderBy = 2;
                getGoodsList();
                break;
            case R.id.tv_privilege:
                if (mScrollBody.getParent() != mLinearBegin) {
                    mMyScrollView.fullScroll(MyScrollView.FOCUS_UP);
                    mLinearStop.removeView(mScrollBody);
                    mLinearBegin.addView(mScrollBody);
                }
                mTv_new.setTextColor(getResources().getColor(R.color.gohere));
                mTv_hot.setTextColor(getResources().getColor(R.color.gohere));
                mTv_privilege.setTextColor(getResources().getColor(R.color.title_red));
                pageNum = 1;
                orderBy = 3;
                getGoodsList();
                break;
        }
    }

    private void getPopupwindow(View v) {
        View popView = View.inflate(context, R.layout.pop_reward_window, null);
        WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth() * 10 / 11;
        popView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        popupWindow = new PopupWindow(popView, width, -2, true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        int[] location = new int[2];
        v.getLocationInWindow(location);  //将v相对屏幕的坐标存入int数组中 int[0] 为 x轴 int[1]为y轴
        Animation animation = AnimationUtils.loadAnimation(context, R.anim.popupwindow);
        popView.startAnimation(animation);
        popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0] + v.getWidth() / 5, location[1] + v.getWidth() * 1 / 2);
//        popupWindow.showAsDropDown(v, -500, -50);  //向右  向上
//        LinearLayout pop_bg = (LinearLayout) popView.findViewById(R.id.pop_bg);
//        pop_bg.setBackgroundResource(R.drawable.pop_elecation);
        NoScrollGridView gv_category = (NoScrollGridView) popView.findViewById(R.id.gv_category);
        CategoryAdapter adapter = new CategoryAdapter(getActivity(), projectItemDatas);
        gv_category.setAdapter(adapter);
        gv_category.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                popupWindow.dismiss();

//                Intent intent = new Intent(context, RewardNewCategoryActivity.class);
//                Intent intent = new Intent(context, HMActivity.class);
//                Bundle bundle = new Bundle();
//                bundle.putInt("position", position);
//                bundle.putSerializable("category", projectItemDatas);
//                intent.putExtras(bundle);
//                intent.putExtra("index", 0);
//                startActivityForResult(intent, REQUESTPOPCODE);
            }
        });
    }

    @Override
    public void onScroll(int scrollY) {
        if (scrollY >= mMeasuredHeight) {
            if (mScrollBody.getParent() != mLinearStop) {
                mLinearBegin.removeView(mScrollBody);
                mLinearBegin.setLayoutParams(new LinearLayout.LayoutParams(mScrollBody.getMeasuredWidth(), mScrollBody.getMeasuredHeight()));
                mLinearStop.addView(mScrollBody);
            }
        } else {
            if (mScrollBody.getParent() != mLinearBegin) {
                mLinearStop.removeView(mScrollBody);
                mLinearBegin.addView(mScrollBody);
            }
        }
    }

    @Override
    public void scrollBottom() {
        if (isMore && CommonTool.isFirstScroll()) {
            pageNum++;
            getGoodsList();
        }
    }
}
